package com.gzm.user.system.service.impl;

import com.gzm.framework.exception.BaseException;
import com.gzm.user.system.entity.vo.LoginUser;
import com.gzm.framework.security.service.TokenService;
import com.gzm.user.system.entity.BUser;
import com.gzm.user.system.entity.vo.LoginUserVO;
import com.gzm.user.system.mapper.BUserMapper;
import com.gzm.user.system.service.BUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author GZM
 * @since 2021-12-27
 */
@Service
public class BUserServiceImpl extends ServiceImpl<BUserMapper, BUser> implements BUserService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManagerBuilder authenticate;

    @Override
    public String login(String username, String password) {

        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticate.getObject().authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BadCredentialsException) {
                throw new BaseException("用户名或密码错误");
            } else {
                throw new BaseException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 前端需要的登陆信息
     * @param loginUser security loginUser
     * @return LoginUserVO
     */
    @Override
    public LoginUserVO getLoginUser(LoginUser loginUser) {
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setToken(loginUser.getToken()).setLoginLocation(loginUser.getLoginLocation())
                .setIpaddr(loginUser.getIpaddr()).setUserId(loginUser.getUser().getId())
                .setUserName(loginUser.getUsername()).setRealName(loginUser.getUser().getRealName());
        return loginUserVO;
    }
}
